package com.atguigu.webflux.controller;

import com.atguigu.webflux.entity.Tutorial;
import com.atguigu.webflux.repositories.TutorialRepository;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Optional;

@RestController
@RequestMapping("/tutorial")
public class TutorialController {
    private final TutorialRepository repository;

    public TutorialController(TutorialRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/findAll")
    public Flux<Tutorial> getAll() {
        return repository.findAll();
    }

    @GetMapping("/published")
    public Flux<Tutorial> getAllPublished() {
        return repository.findByPublished(true);
    }

    @GetMapping("/{id}")
    public Mono<Tutorial> getById(@PathVariable Long id) {
        return repository.findById(id);
    }

    @PostMapping("/")
    public Mono<Tutorial> create(@RequestBody Tutorial tutorial) {
        return repository.save(tutorial);
    }

    @PutMapping("/{id}")
    public Mono<Tutorial> update(@PathVariable Long id, @RequestBody Tutorial tutorial) {
        return repository.findById(id).map(Optional::of).defaultIfEmpty(Optional.empty()).flatMap(optionalTutorial -> {
            if (optionalTutorial.isPresent()) {
                tutorial.setId(id);
                return repository.save(tutorial);
            }

            return Mono.empty();
        });
    }

    @DeleteMapping("/{id}")
    public Mono<Void> deleteTutorial(@PathVariable Long id) {
        return repository.deleteById(id);
    }

    @DeleteMapping("/all")
    public Mono<Void> deleteAll() {
        return repository.deleteAll();
    }
}
